package logic

import (
	"context"
	"encoding/json"

	"googee/common/errorx"
	"googee/service/inbox/api/internal/svc"
	"googee/service/inbox/api/internal/types"
	"googee/service/inbox/rpc/types/inbox"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type OpenmessageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOpenmessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OpenmessageLogic {
	return &OpenmessageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OpenmessageLogic) Openmessage(req *types.OpenMessageReq) (resp *types.OpenMessageReply, err error) {

	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	resp = &types.OpenMessageReply{}

	msg, err := l.svcCtx.Inbox.OpenMessage(l.ctx, &inbox.IdRequest{
		UserId: id,
		Id:     req.Id,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.InvalidArgument {
				return nil, errorx.NewCodeErrorNoMsg(errorx.INBOX_ERROR + 3)
			} else if st.Code() == errorx.UserNotExist {
				return nil, errorx.NewCodeErrorNoMsg(errorx.INBOX_ERROR + 2)
			} else {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	//打开没有错误的时候，可以在这个给用户发送奖励使用dtm的二段消息来做

	copier.Copy(&resp.Data, msg)
	return
}
